import datetime

from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import ReadOnlyModelViewSet, ModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from rest_framework_jwt.views import ObtainJSONWebToken

import constants
from carts.utils import merge_cart_cookie_to_redis
from goods.models import SKU
from goods.serializers import SKUSerializer
from users.models import User, Address
from areas.models import Area
from users.serializers import CreateUserSerializer, UserDetailSerializer, EmailSerializer, AreaSerializer, \
    SubAreaSerializer, UserAddressSerializer, UserPasswordSerializer, AddBrowseHistorySerializer


class UsernameCountView(APIView):
    """判断用户名是否重复"""
    def get(self, request, username):
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count
        }

        return Response(data)


class UserView(CreateAPIView):
    """注册"""
    serializer_class = CreateUserSerializer


class UserDetailView(RetrieveAPIView):
    """用户详情"""
    serializer_class = UserDetailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


class EmailView(UpdateAPIView):
    """更新邮箱"""
    serializer_class = EmailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


class VerifyEmailView(APIView):
    """
    验证邮箱
    请求方式：GET /email/verification/?token=xx
    """
    def get(self, request):
        # 接受地址栏上token参数
        token = request.query_params.get('token')
        # 验证参数
        if not token:
            return Response({'message': '缺少token参数'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证token
        user = User.check_verify_email_token(token)

        if user is None:
            return Response({'message': '链接无效请重新发送短信'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            user.email_active = True
            user.save()
            return Response({'message': 'OK'})


class AreaViewSet(CacheResponseMixin, ReadOnlyModelViewSet):
    """省市区视图"""
    queryset = Area.objects.all()
    serializer_class = AreaSerializer

    def get_serializer_class(self):
        """请求的是城市县区信息"""
        if self.action == 'list':
            return AreaSerializer
        else:
            return SubAreaSerializer

    def get_queryset(self):
        if self.action == 'list':
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()


class AddressViewSet(ModelViewSet):

    queryset = Address.objects.all()
    permission_classes = [IsAuthenticated]
    serializer_class = UserAddressSerializer

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self, request, *args, **kwargs):
        """用户地址列表数据"""
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    def create(self, request, *args, **kwargs):
        """保存用户地址数据"""
        # 检查用户地址数据数目不超过上限
        if self.request.user.addresses.count() > constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super(AddressViewSet, self).create(request, *args, **kwargs)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """设置默认地址"""
        address = self.get_object()
        user = self.request.user
        user.default_address = address
        user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """设置收件人"""
        address = self.get_object()
        address.title = request.data.get('title')
        address.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        """逻辑删除"""
        address = self.get_object()

        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)


class ChangePasswordViewSet(UpdateAPIView):
    """更改密码视图"""

    lookup_field = None
    serializer_class = UserPasswordSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user

    def get_object(self):
        return self.request.user


class BrowseHistoryView(APIView):
    """
    用户浏览记录
    'history_用户id': [sku_id列表]
    """
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user_id = request.user.id
        redis_conn = get_redis_connection('history')
        # 从redis中获取数据
        sku_ids = redis_conn.lrange('history_%s' % user_id, 0, 4)

        # 构造sku对象
        sku_list = []
        for sku_id in sku_ids:
            sku_id = sku_id.decode()
            sku = SKU.objects.get(id=sku_id)
            sku_list.append(sku)

        serializer = SKUSerializer(data=sku_list, many=True)
        serializer.is_valid()
        return Response(serializer.data)

    def post(self, request):
        serializer = AddBrowseHistorySerializer(data=request.data)
        serializer.user = request.user
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


class UserAuthorizeView(ObtainJSONWebToken):
    """自定义用户登录视图，用于合并cookie和redis购物车数据"""
    def post(self, request, *args, **kwargs):
        response = super(UserAuthorizeView, self).post(request, *args, **kwargs)

        serializer = self.get_serializer(data=request.data)
        # 如果登录成功则合并数据
        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            user.last_login = datetime.datetime.now()
            user.save()
            print(user)
            # 合并购物车
            response = merge_cart_cookie_to_redis(request, response, user)

        return response
